﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CivilleWP7.CivilleDataServiceReference;
using System.Data.Services.Client;
using System.Linq;
using System.Collections.Generic;
using System.Data.Linq.SqlClient;


namespace CivilleWP7.Civille.Source
{
    public static class CivilleDataServiceConnector
    {
        private static Uri SvcUri = new Uri("http://civillehostedservices.cloudapp.net:8080/Services/CivilleDataService.svc");
        public static CivilleEntities CivilleContext = new CivilleEntities(CivilleDataServiceConnector.SvcUri);

        //The queries
        public static DataServiceQuery<Task> AllTasksQuery = CivilleDataServiceConnector.CivilleContext.Tasks;
        public static DataServiceQuery<Task> PanoramaTasksQuery;
        public static DataServiceQuery<Task> LocalTasksQuery;
        public static DataServiceQuery<Task> TasksByTypeQuery;
        public static DataServiceQuery<Task> SearchTaskQuery;
        public static DataServiceQuery<CivilleUser> LeaderboardPositionQuery;
        public static DataServiceQuery<CivilleUser> GetUserQuery;
        public static DataServiceQuery<CivilleUser> GetUsersQuery;
        public static DataServiceQuery<CivilleUserToCivilleUser> GetUsersToUsersQuery;
        public static DataServiceQuery<CivilleUser> SearchFriendQuery;
        public static DataServiceQuery<Bonu> GetAllBonusesQuery;
        public static DataServiceQuery<Achievement> GetAllAchievementsQuery;
        public static DataServiceQuery<Reward> GetAllRewardsQuery;
        public static DataServiceQuery<CivilleUserToBonu> GetCompletedBonusesQuery;
        public static DataServiceQuery<CivilleUserToAchievement> GetCompletedAchievementsQuery;
        public static DataServiceQuery<CivilleUserToReward> GetCompletedRewardsQuery;
        public static DataServiceQuery<QRCode> CheckQRCodeQuery;
        public static DataServiceQuery<CivilleUserToReward> ConfirmRewardQuery;
        public static DataServiceQuery<Level> LevelQuery;
        public static DataServiceQuery<Task> UpdateUserPointsQuery;
        public static DataServiceQuery<Level> GetCurrentLevelRequirementsQuery;
        public static DataServiceQuery<MobileUser> RegisterUriForPushNotificationsQuery;
        public static DataServiceQuery<CivilleUserToCivilleUser> GetFriendshipQuery;
        public static DataServiceQuery<TaskHistory> GetTaskHistoryForUserQuery;
        public static DataServiceQuery<Reward> GetRewardsForTask;
        public static DataServiceQuery<TaskHistory> GetTaskHistory;

        public static void InitContext()
        {
            CivilleContext.MergeOption = MergeOption.OverwriteChanges;
            CivilleContext.SendingRequest += (sender, args) =>
            {
                var store = App.Current.Resources["rstrStore"] as SL.Phone.Federation.Utilities.RequestSecurityTokenResponseStore;
                args.RequestHeaders["Authorization"] = "OAuth " + store.SecurityToken;
            };
        }

        public static void SetPanoramaQueryParameters(float latitude, float longitude, float radius)
        {
            var query = from t in CivilleDataServiceConnector.CivilleContext.Tasks
                        where (t.Latitude <= latitude + radius) && (t.Latitude >= latitude - radius)
                        && (t.Longitude <= longitude + radius) && (t.Longitude >= longitude - radius)
                        select t;
            CivilleDataServiceConnector.PanoramaTasksQuery = query as DataServiceQuery<Task>;
        }
        public static void SetTaskQueryParameters(string search, int type)
        {
            DataServiceQuery<Task> query;
            if (type == 0)
            {
                query = (from t in CivilleDataServiceConnector.CivilleContext.Tasks
                         where t.Title.Contains(search) || t.Description.Contains(search)
                         select t)
                            as DataServiceQuery<Task>;
            }
            else
            {
                query = (from t in CivilleDataServiceConnector.CivilleContext.Tasks
                            where (t.Title.Contains(search) || t.Description.Contains(search)) && t.TaskTypeID == type
                            select t)
                            as DataServiceQuery<Task>;
            }
            CivilleDataServiceConnector.SearchTaskQuery = query;
        }

        public static void SetFriendQueryParameters(string friend)
        {
            var query = from t in CivilleDataServiceConnector.CivilleContext.CivilleUsers
                        where t.FirstName.Contains(friend) || t.UserName.Contains(friend) || t.LastName.Contains(friend)
                        select t;
            CivilleDataServiceConnector.SearchFriendQuery = query as DataServiceQuery<CivilleUser>;
        }

        public static void SetLocalQueryParameters(float latitude, float longitude, float radius)
        {
            var query = from t in CivilleDataServiceConnector.CivilleContext.Tasks
                        where (t.Latitude <= latitude + radius) && (t.Latitude >= latitude - radius)
                        && (t.Longitude <= longitude + radius) && (t.Longitude >= longitude - radius)
                        select t;
            CivilleDataServiceConnector.LocalTasksQuery = query as DataServiceQuery<Task>;
        }

        public static void SetTasksByTypeParameters(int type)
        {
            var query = from t in CivilleDataServiceConnector.CivilleContext.Tasks
                        where (t.TaskTypeID == type)
                        select t;
            CivilleDataServiceConnector.TasksByTypeQuery = query as DataServiceQuery<Task>;
        }

        public static void SetLeaderboardPositionParameters()
        {
            var query = from user in CivilleDataServiceConnector.CivilleContext.CivilleUsers
                        orderby user.CurrentLevel descending
                        select user;
            CivilleDataServiceConnector.LeaderboardPositionQuery = query as DataServiceQuery<CivilleUser>;
        }

        public static void SetGetUserParameters(string username)
        {
            DataServiceQuery<CivilleUser> query = (from u in CivilleDataServiceConnector.CivilleContext.CivilleUsers
                                                   where u.UserName.Equals(username)
                                                   select u) as DataServiceQuery<CivilleUser>;
            CivilleDataServiceConnector.GetUserQuery = query;

        }

        public static void SetGetAllBonusesQueryParameters()
        {
            var query = (from b in CivilleDataServiceConnector.CivilleContext.Bonus
                         select b);

            CivilleDataServiceConnector.GetAllBonusesQuery = query as DataServiceQuery<Bonu>;
        }

        public static void SetGetAllAchievementsParameters()
        {
            var query = (from a in CivilleDataServiceConnector.CivilleContext.Achievements
                         select a);

            CivilleDataServiceConnector.GetAllAchievementsQuery = query as DataServiceQuery<Achievement>;
        }

        public static void SetGetAllRewardsParamenters()
        {
            var query = (from r in CivilleDataServiceConnector.CivilleContext.Rewards
                         select r);

            CivilleDataServiceConnector.GetAllRewardsQuery = query as DataServiceQuery<Reward>;
        }

        public static void SetGetCompletedBonusesQueryParameters()
        {
            var query = from utb in CivilleDataServiceConnector.CivilleContext.CivilleUserToBonus
                        where utb.CivilleUserID == UserContext.CurrentUser.ID
                        select utb;

            CivilleDataServiceConnector.GetCompletedBonusesQuery = query as DataServiceQuery<CivilleUserToBonu>;
        }

        public static void SetGetCompletedAchievementsParameters()
        {
            var query = from uta in CivilleDataServiceConnector.CivilleContext.CivilleUserToAchievements
                        where uta.CivilleUserID == UserContext.CurrentUser.ID
                        select uta;

            CivilleDataServiceConnector.GetCompletedAchievementsQuery = query as DataServiceQuery<CivilleUserToAchievement>;
        }

        public static void SetGetCompletedRewardsParamenters()
        {
            var query = from utr in CivilleDataServiceConnector.CivilleContext.CivilleUserToRewards
                        where utr.CivilleUserID == UserContext.CurrentUser.ID
                        select utr;

            CivilleDataServiceConnector.GetCompletedRewardsQuery = query as DataServiceQuery<CivilleUserToReward>;
        }

        public static void SetUsersQueryParameters(int currentUserID)
        {
            var query = (from user in CivilleDataServiceConnector.CivilleContext.CivilleUsers
                         //from con in CivilleDataServiceConnector.CivilleContext.CivilleUserToCivilleUsers
                         //where con.CivilleUser1.UserName.Equals(username)
                         where user.ID != currentUserID
                         select user);

            CivilleDataServiceConnector.GetUsersQuery = query as DataServiceQuery<CivilleUser>;
        }

        public static void SetUsersToUsersQueryParameters(int userID)
        {
            var query = (from con in CivilleDataServiceConnector.CivilleContext.CivilleUserToCivilleUsers
                         where con.CivilleUser.ID == userID
                         select con);

            CivilleDataServiceConnector.GetUsersToUsersQuery = query as DataServiceQuery<CivilleUserToCivilleUser>;
        }

        public static void SetCheckQRCodeQueryParameters(string code, int taskID)
        {
            var query = (from c in CivilleDataServiceConnector.CivilleContext.QRCodes
                         where code.Equals(c.Code) && c.TaskID == taskID && c.Status == true
                         select c);

            CivilleDataServiceConnector.CheckQRCodeQuery = query as DataServiceQuery<QRCode>;
        }

        public static void SetUpdateUserPointsQueryParameters(int taskID)
        {
            var query = (from t in CivilleDataServiceConnector.CivilleContext.Tasks
                         where t.ID == taskID
                         select t);

            CivilleDataServiceConnector.UpdateUserPointsQuery = query as DataServiceQuery<Task>;
        }

        public static void GetCurrentLevelRequirementsQueryParameters(int currentLevel)
        { 
            var query = (from l in CivilleDataServiceConnector.CivilleContext.Levels
                 where l.ID == currentLevel
                 select l);

            CivilleDataServiceConnector.GetCurrentLevelRequirementsQuery = query as DataServiceQuery<Level>;
        }

        public static void RegisterUriForPushNotificationsQueryParameters(string Uri)
        {
            var query = (from mu in CivilleDataServiceConnector.CivilleContext.MobileUsers
                         where mu.URI == Uri
                         select mu);

            CivilleDataServiceConnector.RegisterUriForPushNotificationsQuery = query as DataServiceQuery<MobileUser>;
        }

        public static void SetConfirmRewardQueryParameters(int rewardID)
        {
            var query = from utr in CivilleDataServiceConnector.CivilleContext.CivilleUserToRewards
                        where utr.RewardID == rewardID && utr.CivilleUserID == UserContext.CurrentUser.ID
                        select utr;

            CivilleDataServiceConnector.ConfirmRewardQuery = query as DataServiceQuery<CivilleUserToReward>;
        }

        public static void SetLevelQueryParameters(int levelID)
        {
            var query = from l in CivilleDataServiceConnector.CivilleContext.Levels
                        where l.ID == levelID
                        select l;

            CivilleDataServiceConnector.LevelQuery = query as DataServiceQuery<Level>;
        }


        public static void SetGetFriendshipQueryParameters(int userID, int friendID)
        {
            var query = from f in CivilleDataServiceConnector.CivilleContext.CivilleUserToCivilleUsers
                        where f.UserID == userID && f.FriendID == friendID
                        select f;

            CivilleDataServiceConnector.GetFriendshipQuery = query as DataServiceQuery<CivilleUserToCivilleUser>;
        }

        public static void SetGetTaskHistoryForUserQueryParameters(int userID, int taskID)
        {
            var query = from h in CivilleDataServiceConnector.CivilleContext.TaskHistories
                        where h.UserID == userID && h.TaskID == taskID
                        select h;

            CivilleDataServiceConnector.GetTaskHistoryForUserQuery = query as DataServiceQuery<TaskHistory>;
        }

        public static void SetGetRewardsForTaskQueryParameters(int taskID)
        {
            var query = from r in CivilleDataServiceConnector.CivilleContext.Rewards
                        where r.TaskID == taskID //&& r.ExpiringDate <= System.DateTime.Now
                        select r;

            CivilleDataServiceConnector.GetRewardsForTask = query as DataServiceQuery<Reward>;
        }

        public static void SetTaskHistoryParameters(int userID)
        {
            var query = from th in CivilleDataServiceConnector.CivilleContext.TaskHistories
                        where th.UserID == userID
                        select th;

            CivilleDataServiceConnector.GetTaskHistory = query as DataServiceQuery<TaskHistory>;
        }
    }
}
